package top.lyjwn.todo.common.context;

import jakarta.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * 获取spring容器，以访问容器中定义的其他bean
 */
@Component
public class SpringContext {

	@Autowired
	private HttpServletRequest httpServletRequest;

	/**
	 * 获取对象
	 * 
	 * @return Object 一个以所给名字注册的bean的实例 (service注解方式，自动生成以首字母小写的类名为bean name)
	 */
	public Object getBean(String name) {
		BeanFactory factory = WebApplicationContextUtils
				.getRequiredWebApplicationContext(httpServletRequest.getServletContext());
		return factory.getBean(name);

	}

	/**
	 * 获取对象,未加载bean的时候调用
	 * 
	 * @return Object 一个以所给名字注册的bean的实例 (service注解方式，自动生成以首字母小写的类名为bean name)
	 */
	public static Object getBean(String name, HttpServletRequest httpServletRequest) {
		BeanFactory factory = WebApplicationContextUtils
				.getRequiredWebApplicationContext(httpServletRequest.getServletContext());
		return factory.getBean(name);

	}

}
